
// task_transaction_record_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/mine/transaction/task_transaction_record_page_vm.dart';
import 'task_transaction_record_cell.dart';

class TaskTransactionRecordPage extends StatefulWidget {
  final TaskRecordType type;
  final int category;

  const TaskTransactionRecordPage({
    Key? key,
    required this.type,
    required this.category,
  }) : super(key: key);

  @override
  State<TaskTransactionRecordPage> createState() =>
      _TaskTransactionRecordPageState();
}

class _TaskTransactionRecordPageState extends State<TaskTransactionRecordPage> {
  late TaskTransactionRecordViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = TaskTransactionRecordViewModel(
      type: widget.type,
      category: widget.category,
    );
    // 初始加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _viewModel.loadData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: _viewModel,
      child: Consumer<TaskTransactionRecordViewModel>(
        builder: (context, viewModel, child) {
          return _buildContent(viewModel);
        },
      ),
    );
  }

  Widget _buildContent(TaskTransactionRecordViewModel viewModel) {
    if (viewModel.hasError && viewModel.monthList.isEmpty) {
      return _buildErrorView(viewModel);
    }

    if (viewModel.monthList.isEmpty && !viewModel.isLoading) {
      return _buildEmptyView();
    }

    return _buildListView(viewModel);
  }

  Widget _buildListView(TaskTransactionRecordViewModel viewModel) {
    return NotificationListener<ScrollNotification>(
      onNotification: (scrollNotification) {
        if (scrollNotification is ScrollEndNotification) {
          final metrics = scrollNotification.metrics;
          if (metrics.atEdge && metrics.pixels != 0) {
            if (!viewModel.hasNoMoreData && !viewModel.isLoadingMore) {
              viewModel.loadMore();
            }
          }
        }
        return false;
      },
      child: CustomScrollView(
        slivers: [
          if (viewModel.isRefreshing)
            const SliverToBoxAdapter(
              child: _LoadingIndicator(),
            ),
          ..._buildRecordSections(viewModel),
          if (viewModel.isLoadingMore)
            const SliverToBoxAdapter(
              child: _LoadingIndicator(),
            ),
          if (viewModel.hasNoMoreData && viewModel.monthList.isNotEmpty)
            const SliverToBoxAdapter(
              child: _NoMoreDataIndicator(),
            ),
        ],
      ),
    );
  }

  List<Widget> _buildRecordSections(TaskTransactionRecordViewModel viewModel) {
    return viewModel.monthList.map((month) {
      final records = viewModel.monthDataMap[month] ?? [];

      return SliverList(
        delegate: SliverChildBuilderDelegate(
              (context, index) {
            if (index == 0) {
              return _buildSectionHeader(month, viewModel);
            }
            final recordIndex = index - 1;
            return TaskTransactionRecordCell(
              model: records[recordIndex],
              showBottomLine: recordIndex < records.length - 1,
            );
          },
          childCount: records.length + 1, // +1 for header
        ),
      );
    }).toList();
  }

  Widget _buildSectionHeader(String month, TaskTransactionRecordViewModel viewModel) {
    return Container(
      height: 35,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      color: const Color(0xFFF5F5F5),
      child: Row(
        children: [
          Text(
            month,
            style: const TextStyle(
              fontSize: 13,
              color: Color(0xFF666666),
              fontWeight: FontWeight.w500,
            ),
          ),
          const Spacer(),
          GestureDetector(
            onTap: _showDatePicker,
            child: const Icon(
              Icons.arrow_drop_down,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  void _showDatePicker() {
    final viewModel = Provider.of<TaskTransactionRecordViewModel>(context, listen: false);

    showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
      initialDatePickerMode: DatePickerMode.year,
    ).then((selectedDate) {
      if (selectedDate != null) {
        viewModel.selectTime(selectedDate);
      }
    });
  }

  Widget _buildEmptyView() {
    return Container(
      height: MediaQuery.of(context).size.height - 200,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.receipt_long,
              size: 60,
              color: Colors.grey[300],
            ),
            const SizedBox(height: 16),
            Text(
              '暂无记录',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorView(TaskTransactionRecordViewModel viewModel) {
    return Container(
      height: MediaQuery.of(context).size.height - 200,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 60,
              color: Colors.grey[300],
            ),
            const SizedBox(height: 16),
            Text(
              viewModel.errorMessage,
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[500],
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                viewModel.clearError();
                viewModel.refresh();
              },
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }
}

class _LoadingIndicator extends StatelessWidget {
  const _LoadingIndicator();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: const Center(
        child: CircularProgressIndicator(),
      ),
    );
  }
}

class _NoMoreDataIndicator extends StatelessWidget {
  const _NoMoreDataIndicator();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: const Center(
        child: Text(
          '没有更多数据了',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ),
    );
  }
}

enum TaskRecordType {
  coin, // 金币记录
  cash, // 现金记录
}